"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : CLEAN CONNECTION
Case Name   : CLEAN CONNECTION TO ALL FOR DATABASE 指定不存在的dbname，合理报错
Create At   : 2022-05-10
@zou_jialiang0501125467
Description :
    1、删除数据库
    2、执行清理操作
    3、清理环境
Expect      :
    1、删除数据库成功
    2、执行清理操作合理报错
    3、清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CleanConnection(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.db_name = 'd_clean_0013'

    def test_main(self):
        step1_txt = '----step1: 删除数据库，expect: 成功----'
        self.log.info(step1_txt)
        sql1 = f'drop database if exists {self.db_name};'
        msg1 = self.pri_sh.execut_db_sql(sql1)
        self.log.info(msg1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, msg1,
                      '执行失败:' + step1_txt)

        step2_txt = '----step2: 执行清理操作，expect: 合理报错----'
        self.log.info(step2_txt)
        sql2 = f'clean connection to all for database {self.db_name};'
        msg2 = self.pri_sh.execut_db_sql(sql2)
        self.log.info(msg2)
        self.assertIn(f'ERROR:  database "{self.db_name}" does not exist',
                      msg2, '执行失败:' + step2_txt)

    def tearDown(self):
        self.log.info('----this is teardown----')
        step3_txt = '----step3: 删除数据库----'
        self.log.info(step3_txt)
        drop_sql = f'drop database if exists {self.db_name};'
        drop_result = self.pri_sh.execut_db_sql(drop_sql)
        self.log.info(drop_result)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_result,
                      "执行失败" + step3_txt)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
